<template>
  <view>
    <xl-navbar v-if="title" :title="title" :shadow="true" :fixed="false" :zIndex="998"></xl-navbar>
    <view class="xl-address-search-box">
      <xl-search v-model="keywords" style="width: 100%;" @search="handleSearch"></xl-search>
    </view>
    <view class="xl-address-list">
      <xl-load-refresh
          ref="loadRefresh"
          padding="10rpx 0 0"
          refresh
          :pageSize="props.list ? props.list.length + 1 : 10"
          :fixed="true"
          :lazyLoad="true"
          :reduceHeight="props.title ? 340 : 250"
          @provider="provider"
      >
        <template v-slot:list="{ items }">
          <!-- 数据列表 -->
          <view
              v-for="address in items"
              :key="address[propNameConfig.id]"
              class="xl-address-item-box"
              @click="clickAddress(address)"
          >
            <view class="xl-address-item">
              <view class="xl-address-item-info">
                <view class="info">
                  <text class="name">{{ address[propNameConfig.name] }}</text>
                  <text class="tel">{{ address[propNameConfig.tel] }}</text>
                  <view v-if="address[propNameConfig.isDefault]" class="tag">默认</view>
                </view>
                <view class="address">
                  <text v-if="address.region">{{ address.region }}</text>
                  <text>{{ address.address }}</text>
                </view>
              </view>
              <view class="xl-address-edit">
                <xl-icon name="xl-edit" :size="22" @click.stop="editAddress(address)"></xl-icon>
              </view>
            </view>
            <view v-if="manage || showManage" class="xl-address-manage">
              <view class="check-box" :class="{ check: address[propNameConfig.isDefault] }" @click="changeDefaultAddress(address)">
                <xl-icon name="xl-yes" color="#fff" :size="13"></xl-icon>
              </view>
              <view>默认地址</view>
              <view class="btn-box">
                <view class="btn" @click.stop="copyAddress(address)">
                  <xl-icon name="xl-daipingjia" :size="16" color="#b1b1b1" right="4rpx"></xl-icon>
                  <text>复制</text>
                </view>
                <view class="btn" @click.stop="editAddress(address)">
                  <xl-icon name="xl-daipingjia" :size="16" color="#b1b1b1C" right="4rpx"></xl-icon>
                  <text>编辑</text>
                </view>
                <view class="btn" @click.stop="deleteAddress(address, index)">
                  <xl-icon name="xl-daipingjia" :size="16" color="#b1b1b1" right="4rpx"></xl-icon>
                  <text>删除</text>
                </view>
              </view>
            </view>
          </view>
        </template>
      </xl-load-refresh>
      <view class="xl-address-footer">
        <xl-button
            v-if="!manage || showManage"
            width="240rpx"
            height="80rpx"
            :text="showManage ? '完成' : '管理'"
            color="#888"
            textColor="#333"
            shape="circle"
            plain
            @click="showManage = !showManage"
        ></xl-button>
        <xl-button
            :width="manage ? '640rpx' : '400rpx'"
            height="80rpx"
            :disabled="showManage"
            :text="btnText"
            :color="color"
            :textColor="btnTextColor"
            shape="circle"
            @click="addAddress"
        ></xl-button>
      </view>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <page-container v-if="popup && showPopup" :show="showPopup" :overlay="false" :custom-style="pageContainerStyle" :z-index="999" @beforeleave="beforeLeave">
      <!-- #endif -->
      <!-- #ifndef MP-WEIXIN -->
      <xl-popup v-if="popup" v-model="showPopup" direction="right" padding="0" :statusBar="false">
        <!-- #endif -->
        <xl-address-form
            :address-api="addressApi"
            :address-id="curAddressId"
            :propNames="propNameConfig"
            :text="btnText"
            :color="color"
            :textColor="btnTextColor"
            :routerBack="!popup"
            @load="loadAddress"
            @close="showPopup = false"
            @submit="submit"
        />
        <!-- #ifdef MP-WEIXIN -->
    </page-container>
    <!-- #endif -->
    <!-- #ifndef MP-WEIXIN -->
    </xl-popup>
    <!-- #endif -->
  </view>
</template>

<script setup>
import XlAddressForm from '../xl-address-form/xl-address-form.vue'
import { ref, computed, watch, nextTick } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { completeProvince, completeCity } from '../../libs/utils/addressParse.js'
import propsData from './props'

const props = defineProps(propsData)
const emits = defineEmits(['load', 'changeDefault', 'delete', 'edit', 'submit','click'])

// #ifdef MP-WEIXIN
const pageContainerStyle = computed(() => {
  return `width: 750rpx; height: ${uni.getWindowInfo().screenHeight}px`
})
// #endif

// 配置
const propNameConfig =  {
  id: props.propNames?.id || 'id',
  name: props.propNames?.name || 'name',
  tel: props.propNames?.tel || 'tel',
  province: props.propNames?.province || 'province',
  city: props.propNames?.city || 'city',
  district: props.propNames?.district || 'district',
  address: props.propNames?.address || 'address',
  isDefault: props.propNames?.isDefault || 'isDefault',
  lng: props.propNames?.lng || 'lng',
  lat: props.propNames?.lat || 'lat'
}

const loadRefresh = ref()
const showManage = ref(false)
const keywords = ref('')
onShow(() => nextTick(() => {
  if(props.list) {
    watch(() => props.list, newVal => {
      pushAddress(newVal, loadRefresh.value.push)
    }, { immediate: true })
  } else {
    loadRefresh.value.reload()
  }
}))

function handleSearch() {
  loadRefresh.value.reload()
}

function provider(pageInfo, push) {
  if(props.listApi) {
    uni.$xl.apis[props.listApi]({
      params: {
        pageIndex: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        keywords: keywords.value
      }
    }).then(res => {
      pushAddress(res.data.records, push)
    }).catch(err => {
      uni.$xl.toast(err, 2000)
    })
  } else {
    emits('load', { ...pageInfo, keywords: keywords.value }, data => pushAddress(data, push))
  }
}

function pushAddress(list, pushFn) {
  pushFn(list.map(item => {
    if(item[propNameConfig.province] === item[propNameConfig.city]) {
      item.region = completeProvince(item[propNameConfig.province]) + item[propNameConfig.district]
    } else {
      item.region = completeProvince(item[propNameConfig.province]) + completeCity(item[propNameConfig.city]) + item[propNameConfig.district]
    }
    return item
  }))
}

// 是否显示表单弹窗
const showPopup = ref(false)
const curAddressId = ref('')
// 新增地址
function addAddress() {
  if(props.popup) {
    curAddressId.value = ''
    showPopup.value = true
  } else {
    emits('add')
  }
}
// 修改地址
function editAddress(address) {
  if(props.popup) {
    curAddressId.value = address[propNameConfig.id]
    showPopup.value = true
  } else {
    emits('edit', address)
  }
}
// 打开修改弹窗 触发地址加载事件
function loadAddress(addressId, handleData) {
  emits('edit', addressId, handleData)
}

function deleteAddress(address, index) {
  uni.$xl.showModal({
    content: '是否确认删除该地址？',
    confirmColor: props.themeColor
  }).then(res => {
    if(props.deleteApi) {
      uni.$xl.apis[props.deleteApi]({
        jointUrl: '/' + address.id
      }).then(res => {
        uni.$xl.toast('删除成功')
        done()
      }).catch(err => {
        uni.$xl.toast('删除失败：' + err)
      })
    } else {
      emits('delete', address[propNameConfig.id], done)
    }
  })
  // 完成删除调用
  function done() {
    loadRefresh.value.deleteData(index)
  }
}
// 复制地址
function copyAddress(address) {
  let text = `收件人: ${address[propNameConfig.name]}
手机号码: ${address[propNameConfig.tel]}
所在地区: ${address[propNameConfig.province]}${address[propNameConfig.city]}${address[propNameConfig.district]}
详细地址: ${address[propNameConfig.address]}`
  uni.setClipboardData({
    data: text,
    success() {
      uni.$xl.toast('复制成功')
    },
    fail(err) {
      console.log(err);
      console.log('地址复制失败');
    }
  });
}
// 切换默认地址
function changeDefaultAddress(address) {
  if(!address[propNameConfig.isDefault]) {
    loadRefresh.value.getData().forEach(addr => {
      addr[propNameConfig.isDefault] = false
    })
  }
  address[propNameConfig.isDefault] = !address[propNameConfig.isDefault]
  emits('changeDefault', address[propNameConfig.id], address[propNameConfig.isDefault])
}
// 提交地址表单
function submit(address) {
  emits('submit', address, () => {
    // 提交成功调用
    showPopup.value = false
    loadRefresh.value.reload()
  }, loadRefresh.value.push)
}
// 点击地址
function clickAddress(address) {
  emits('click', address)
}

// #ifdef MP-WEIXIN
function beforeLeave() {
  showPopup.value = false
}
// #endif
</script>

<style lang="scss" scoped>
.xl-address-list {
  --theme-color: v-bind(color);
  &::before{
    content: '';
    display: table;
  }
}
.xl-address-search-box {
  width: 750rpx;
  height: 120rpx;
  padding: 0 24rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}
.xl-address-item-box {
  box-sizing: border-box;
  width: 690rpx;
  margin: 0 auto 40rpx;
  box-shadow: 0rpx 2rpx 10rpx rgba(0, 0, 0, 0.1);
  background-color: #fff;
  border-radius: 12rpx;
}
.xl-address-item {
  display: flex;
  height: 102rpx;
  padding: 30rpx;
}
.xl-address-item-info {
  flex: 1;
  .info {
    display: flex;
    align-items: center;
  }
  .name {
    font-weight: 700;
    font-size: 34rpx;
    margin-right: 20rpx;
  }
  .tel {
    font-size: 30rpx;
    color: #333;
  }
  .tag {
    border: 1rpx solid $main-color;
    color: $main-color;
    font-size: 20rpx;
    border-radius: 6rpx;
    margin-right: 10rpx;
    padding: 2rpx 8rpx;
    margin-left: 20rpx;
  }
  .address {
    margin-top: 14rpx;
    line-height: 1.5;
    color: #444;
    font-size: 28rpx;
  }
}
.xl-address-edit {
  margin-left: 20rpx;
  display: flex;
  align-items: center;
}
.xl-address-manage {
  border-top: 1rpx solid #f1f1f1;
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  color: #888888;
  font-size: 27rpx;
  .check-box {
    overflow: hidden;
    width: 26rpx;
    height: 26rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2rpx solid #888888;
    color: #fff;
    margin-right: 16rpx;
    &.check {
      border-color: var(--theme-color);
      background-color: var(--theme-color);
    }
  }
  .btn-box {
    display: flex;
    align-items: center;
    margin-left: auto;
    .btn {
      margin-left: 24rpx;
      color: #888888;
      font-size: 26rpx;
    }
  }
}
.xl-address-footer {
  background-color: #fff;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 30rpx;
  width: 750rpx;
  height: 130rpx;
  padding: 0 40rpx;
  box-shadow: 0px 2rpx 6rpx 0px rgba(0,0,0,0.2) ;
}
</style>